import SparkMD5 from 'spark-md5'

self.onmessage = async (e) => {
  const { file, chunks } = e.data

  const [fileHash, chunksHash] = await Promise.all([handleFileHash(file), handleChunkHash(chunks)])

  self.postMessage({ type: 'success', fileHash, chunksHash })
}
function handleFileHash(file: File) {
  const fileMD5 = new SparkMD5.ArrayBuffer() // 构建hash值对象
  const reader = new FileReader()

  return new Promise((resolve, reject) => {
    reader.readAsArrayBuffer(file)

    reader.onload = (event) => {
      fileMD5.append(reader.result as ArrayBuffer)
      const result = fileMD5.end()
      resolve(result)
    }
  })
}

function handleChunkHash(chunks: Blob[]) {
  let chunksHash: string[] = []
  const chunkMD5 = new SparkMD5.ArrayBuffer() // 构建hash值对象
  let processed = 0
  const chunkTotal = chunks.length
  return new Promise((resolve, reject) => {
    const processChunk = (index: number) => {
      if (index >= chunkTotal) {
        resolve(chunksHash)
        return
      }

      // 读取文件
      const reader = new FileReader()
      // 指定读取的文件
      reader.readAsArrayBuffer(chunks[index])

      reader.onload = (event) => {
        chunkMD5.append(reader.result as ArrayBuffer)
        processed++

        const result = chunkMD5.end()
        chunksHash.push(result)
        processChunk(index + 1)
      }

      reader.onerror = (error) => {
        self.postMessage({ type: 'error', error })
      }
    }

    processChunk(0)
  })
}
